package cn.lzj.ymcc.mq;

import cn.lzj.ymcc.constants.RocketMQConstants;
import cn.lzj.ymcc.domain.MessageStation;
import cn.lzj.ymcc.dto.SendStation2MQDto;
import cn.lzj.ymcc.result.JSONResult;
import cn.lzj.ymcc.service.IMessageSmsService;
import cn.lzj.ymcc.service.IMessageStationService;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.MessageModel;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;
import java.util.Date;

@Slf4j
@Component
@RocketMQMessageListener(
        //topic名称
        topic = RocketMQConstants.ROKETMQ_TOPIC_STATION_SENDMQMEESAGE,
        //消费者组名
        selectorExpression = RocketMQConstants.ROKETMQ_TAGS_STATION_SENDMQMEESAGE,
        consumerGroup = "service-common-consumer-sendstation")
public class RocketMQConsumer implements RocketMQListener<MessageExt> {
    @Autowired
    private IMessageStationService messageStationService;

    @Override
    public void onMessage(MessageExt messageExt) {

        if(messageExt.getBody()==null||messageExt.getBody().length==0) {
            return;
        }

        String s = new String(messageExt.getBody(), StandardCharsets.UTF_8);
        SendStation2MQDto mqDto = JSON.parseObject(s, SendStation2MQDto.class);

        //保存站内信
        Date nowTime = new Date();
        MessageStation messageStation = new MessageStation(
                null,mqDto.getTitle(),mqDto.getContent(),
                mqDto.getType(),nowTime,0,null
        );
        mqDto.getUserIds().forEach(userId->{
            messageStation.setUserId(userId);
            messageStationService.insert(messageStation);
            log.info("保存在站内信{}",messageStation);
        });


    }
}
